package com.learn.handle;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class DownloadHandler {

    @Autowired
    ServletContext servletContext;

    @RequestMapping("/download/handler")
    public ResponseEntity<byte[]> downloadHandler() {

        InputStream is = servletContext.getResourceAsStream("/download/3zmrjd.png");

        try {
            byte[] buffer = new byte[is.available()];

            is.read(buffer);
            MultiValueMap responseHeaderMap = new HttpHeaders();

            responseHeaderMap.set("Content-Disposition", "attachment; filename=3zmrjd.png");

            ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(buffer, responseHeaderMap, HttpStatus.OK);

            return responseEntity;
        } catch (IOException e) {
            throw new RuntimeException(e);

        }finally {
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
